package com.banciyuan.bcywebview.biz.main.mineinfo.message;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.MessageApi;
import com.banciyuan.bcywebview.api.SpecialApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshScrollView;
import com.banciyuan.bcywebview.biz.main.group.focused.FocusedGroupActivity;
import com.banciyuan.bcywebview.biz.main.message.messagedetail.MessageBroadCastActivity;
import com.banciyuan.bcywebview.biz.main.message.messagedetail.MessageDetailActivity;
import com.banciyuan.bcywebview.biz.topic.TopicDetailListActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.NotificationCount;
import de.greenrobot.daoexample.model.Special;

/**
 * Created by hy on 2016/4/6.
 */
public class MessageActivity extends BaseActivity implements View.OnClickListener {
    private RequestQueue mQueue;
    private ImageLoader imageLoader;

    private TextView tvCommentNumCount;
    private TextView tvRemindNumCount;
    private TextView tvSerializeNumCount;
    private TextView tvBroadCastNumCount;
    private TextView tvGroupNumCount;

    private PullToRefreshScrollView refreshView;
    private TextView tvTopicFooterTitle;
    private ImageView ivTopicGFooterImg;
    private ProgressbarHelper mProgressbarHelper;
    private NotificationCount notificationCount;

    private static final int MESSAGE_OTHER = 1080;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        getFirstTopicItem();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.my_message));
    }

    @Override
    protected void initUi() {
        findViewById(R.id.rl_comment).setOnClickListener(this);
        findViewById(R.id.rl_remind).setOnClickListener(this);
        findViewById(R.id.rl_serialize).setOnClickListener(this);
        findViewById(R.id.rl_special).setOnClickListener(this);
        findViewById(R.id.rl_broadcast).setOnClickListener(this);
        findViewById(R.id.rl_group).setOnClickListener(this);
        refreshView = (PullToRefreshScrollView) findViewById(R.id.refreshview);
        tvCommentNumCount = (TextView) findViewById(R.id.tv_commentnum_count);
        tvRemindNumCount = (TextView) findViewById(R.id.tv_remindnum_count);
        tvSerializeNumCount = (TextView) findViewById(R.id.tv_serializenum_count);
        tvBroadCastNumCount = (TextView) findViewById(R.id.tv_broadcast_count);
        tvTopicFooterTitle = (TextView) findViewById(R.id.topic_footer_title);
        ivTopicGFooterImg = (ImageView) findViewById(R.id.topic_footer_img);
        tvGroupNumCount = (TextView) findViewById(R.id.tv_group_count);
    }

    @Override
    protected void initAction() {
        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + MessageApi.getNoticecount();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, MessageActivity.this)) {
                    try {
                        String data = new JSONObject(response).getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        notificationCount = gson.fromJson(data, NotificationCount.class);
                        processNotificationData();
                        mProgressbarHelper.onSuccess();
                        refreshView.onRefreshComplete();
                    } catch (Exception e) {
                        mProgressbarHelper.onFailed();
                        refreshView.onRefreshComplete();
                    }
                } else {
                    mProgressbarHelper.onFailed();
                    refreshView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                refreshView.onRefreshComplete();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processNotificationData() {
        if (StringUtil.notNullEqual(notificationCount.getNotify(), "0")) {
            tvCommentNumCount.setVisibility(View.INVISIBLE);
            FlagUtils.ifNotifyUpdate = false;
        } else {
            tvCommentNumCount.setVisibility(View.VISIBLE);
            tvCommentNumCount.setText(notificationCount.getNotify());
            FlagUtils.ifNotifyUpdate = true;
        }
        if (StringUtil.notNullEqual(notificationCount.getRemind(), "0")) {
            tvRemindNumCount.setVisibility(View.INVISIBLE);
            FlagUtils.ifRemindUpdate = false;
        } else {
            tvRemindNumCount.setVisibility(View.VISIBLE);
            tvRemindNumCount.setText(notificationCount.getRemind());
            FlagUtils.ifRemindUpdate = true;
        }
        if (StringUtil.notNullEqual(notificationCount.getNovel_update(), "0")) {
            tvSerializeNumCount.setVisibility(View.INVISIBLE);
            FlagUtils.ifSerializeUpdate = false;
        } else {
            tvSerializeNumCount.setVisibility(View.VISIBLE);
            tvSerializeNumCount.setText(notificationCount.getNovel_update());
            FlagUtils.ifSerializeUpdate = true;
        }
        if (StringUtil.notNullEqual(notificationCount.getAnnounce(), "0")) {
            tvBroadCastNumCount.setVisibility(View.INVISIBLE);
            FlagUtils.ifAnnounce = false;
        } else {
            tvBroadCastNumCount.setVisibility(View.VISIBLE);
            tvBroadCastNumCount.setText(notificationCount.getAnnounce());
            FlagUtils.ifAnnounce = true;
        }
        if (StringUtil.notNullEqual(notificationCount.getGroup(), "0")) {
            tvGroupNumCount.setVisibility(View.INVISIBLE);
            FlagUtils.ifGroupUpdate = false;
        } else {
            tvGroupNumCount.setVisibility(View.VISIBLE);
            tvGroupNumCount.setText(notificationCount.getGroup());
            FlagUtils.ifGroupUpdate = true;
        }
    }

    private void getFirstTopicItem() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, "1"));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, "1"));
        String url = HttpUtils.BASE_URL + SpecialApi.getSpecials();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, MessageActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray data = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<Special> temp = gson.fromJson(data.toString(), new TypeToken<List<Special>>() {
                        }.getType());
                        if (!temp.isEmpty()) {
                            dealJson(temp);
                        }

                    } catch (JSONException e) {
                        mProgressbarHelper.onFailed();
                        refreshView.onRefreshComplete();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                refreshView.onRefreshComplete();
            }
        };
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private void dealJson(List<Special> temp) {
        if (null != temp && temp.size() > 0) {
            Special special = temp.get(0);
            imageLoader.displayImage(special.getCover_link(), ivTopicGFooterImg, ImageOptions.options);
            tvTopicFooterTitle.setText(Html.fromHtml(special.getTitle()));
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.rl_comment:
                intent = new Intent(this, MessageDetailActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, MessageDetailActivity.MESSAGE_NOTIFY);
                startActivityForResult(intent, MESSAGE_OTHER);
                break;
            case R.id.rl_remind:
                intent = new Intent(this, MessageDetailActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, MessageDetailActivity.MESSAGE_REMIND);
                startActivityForResult(intent, MESSAGE_OTHER);
                break;
            case R.id.rl_serialize:
                intent = new Intent(this, MessageDetailActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, MessageDetailActivity.MESSAGE_NOVEL);
                startActivityForResult(intent, MESSAGE_OTHER);
                break;
            case R.id.rl_special:
                intent = new Intent(this, TopicDetailListActivity.class);
                startActivityForResult(intent, MESSAGE_OTHER);
                break;
            case R.id.rl_broadcast:
                intent = new Intent(this, MessageBroadCastActivity.class);
                startActivityForResult(intent, MESSAGE_OTHER);
                break;
            case R.id.rl_group:
                intent = new Intent(this, FocusedGroupActivity.class);
                startActivityForResult(intent, MESSAGE_OTHER);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MESSAGE_OTHER) {
            initData();
        }
    }
}
